package it.uiip.crm.persistenza;

import it.uiip.crm.model.Utente;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

public class DAOUtente {
	
	public static List<Utente> findAllUtenti() throws DAOException {
        
        try {
            Session session = PersistenceManager.getSession();

            Query query = session.createQuery("from Utente");
            return query.list();
            
        } catch (HibernateException e) {
            throw new DAOException(e);        
        }

    }

	public static Utente findByEmail(String email) throws DAOException {
        Utente utente = null;
        try {
            Session session = PersistenceManager.getSession();
            Query query = session.createQuery("from Utente where email = ?");
            query.setString(0, email);
            List<Utente> risultato = query.list();
            if (risultato.size() != 0) {
            	utente = risultato.get(0);
            }
        } catch (HibernateException e) {
            throw new DAOException(e);
        }
        return utente;
    }
    
	public static boolean findFirstUser() throws DAOException {
        try {
            Session session = PersistenceManager.getSession();

            Query query = session.createQuery("from Utente");

            List<Utente> risultato = query.list();
            return risultato.size()==0;
        } catch (HibernateException e) {
            throw new DAOException(e);
        }
    }

    public static void makeRefresh(Utente utente) throws DAOException {
        PersistenceManager.beginTransaction();
        try {
            PersistenceManager.refreshObject(utente);
        } catch (HibernateException e) {
            PersistenceManager.rollbackTransaction();
            throw new DAOException(e);
        }
    }
    
    public static void makePersistent(Utente utente) throws DAOException {
        PersistenceManager.beginTransaction();
        try {
            PersistenceManager.getSession().saveOrUpdate(utente);
            PersistenceManager.commitTransaction();
        } catch (HibernateException e) {
            PersistenceManager.rollbackTransaction();
            throw new DAOException(e);
        }
    }
    
    public static void makeTransient(Utente utente) throws DAOException {
        PersistenceManager.beginTransaction();
        try {
            PersistenceManager.getSession().delete(utente);
            PersistenceManager.commitTransaction();
        } catch (HibernateException e) {
            PersistenceManager.rollbackTransaction();
            throw new DAOException(e);
        }
    }
}
